package com.example.springboot_code_read.propertyEditor;

import com.example.springboot_code_read.bean.MyObj;
import javafx.scene.input.DataFormat;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PropertyEditorTest {

    public static void main(String[] args) {

        BeanWrapperImpl beanWrapper = new BeanWrapperImpl(MyObj.class);

        beanWrapper.overrideDefaultEditor(Date.class, new MyCustomEditor());

        beanWrapper.setPropertyValue("date", "2023-12-5");

        beanWrapper.setPropertyValue("path", "/opt/spring-reading");

        System.out.println("MyObj=" + beanWrapper.getWrappedInstance());

    }

    public static class MyCustomEditor extends PropertyEditorSupport {

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-DD");

        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            try {
                setValue(dateFormat.parse(text));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public String getAsText() {
            Date value = (Date) getValue();
            return value != null ? dateFormat.format(value) : "";
        }
    }

}
